package dinosaur;

import java.awt.*;
import java.awt.image.BufferedImage;

public class Bird extends Barrier {

    private BufferedImage bird1;
    private BufferedImage bird2;
    private int time;
    private int fresh = DinosaurMain.FRESH;

    public Bird(BufferedImage bird1, BufferedImage bird2, GamePane pane) {
        setToPane(pane);
        this.bird1 = bird1;
        this.bird2 = bird2;
        setTempImage(bird1);
        setY(DinosaurThread.LOWER_Y - bird1.getHeight() / 4 * 3);
        setX(GamePane.FULL_WINDOW_WIDTH);
    }

    @Override
    public void run() {
        threadSleep(4700); //鸟儿不要马上来，过一会(10s)才来
        while (DinosaurMain.state != DinosaurMain.GAME_OVER) {
            if (DinosaurMain.state == DinosaurMain.PLAYING)
                roll();
            pane.repaint();
        }
    }

    @Override
    public void roll() {
        if (getX() < -1 * getTempImage().getWidth()) {
            threadSleep(10000);
            setX(GamePane.FULL_WINDOW_WIDTH);
        } else {
            time = time >= (100 * 2 * 2) ? 0 : time;//防止溢出
            int temp = time / (100 * 2) % 2;//time每计算20次换一张
            switch (temp) {
                case 0:
                    setTempImage(bird1); //第1张
                    threadSleep(DinosaurThread.millis);
                    break;
                case 1:
                    setTempImage(bird2); //第2张
                    threadSleep(DinosaurThread.millis);
                    break;
            }
            time += fresh;
            setX(getX() - DinosaurMain.speed * 2);//鸟儿以2倍速speed向左移动
        }

        pane.repaint();
        try {
            sleep(10); //线程休眠刷新时间间隔，默认10ms
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //    Rectangle methods
    public Rectangle boundBird(){
        return new Rectangle(getX(),getY(),getBarryWidth(),getBarryHeigh());
    }

    public Rectangle boundBirdHead(){
//        bird的头部
        return new Rectangle(getX()+5,getY()+5,getBarryWidth()/3-5,getBarryHeigh()/2-5);
    }

    public Rectangle boundBirdBody(){
//        bird的身体
        return new Rectangle(getX()+getBarryWidth()/3+5,getY()+5,getBarryWidth()/3-5,getBarryHeigh()-5);
    }
}
